package com.yisin.pbox.www.common.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.mysql.jdbc.StringUtils;
import com.yisin.pbox.frame.util.FileUtils;
import com.yisin.pbox.frame.util.StringUtil;
import com.yisin.pbox.www.common.frame.BaseAction;

/**
 * @简述：<一句话介绍>
 * @详述：<详细介绍>
 * @author admin
 * @since 1.0
 */
@SuppressWarnings("serial")
public class UploadFileAction extends BaseAction {

	private File uploadFile;
	private String fileName;
	private String version;
	private String key;
	private float fileMaxSize = 204800;
	public String dirName = "attachment/";

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	private String fileSavePath = "/";

	public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	/**
	 * 设置文件保存路径
	 * 
	 * @param request
	 */
	public void setFileSavePath(HttpServletRequest request) {
		if (null != genre) {
			String spath = request.getServletContext().getRealPath("/");
			int index = spath.lastIndexOf("\\");
			fileSavePath = (index != -1 ? spath.substring(0, index) : spath)
					+ "/" + dirName + "/";
			fileSavePath = fileSavePath.replaceAll("\\\\", "/");
			fileSavePath = fileSavePath.replaceAll("///", "/");
			fileSavePath = fileSavePath.replaceAll("//", "/");
			FileUtils.createDir(fileSavePath);
		}
	}
	
	public void setFileSavePath2(HttpServletRequest request) {
		if (null != genre) {
			String spath = request.getServletContext().getRealPath("/");
			int index = spath.lastIndexOf("\\");
			fileSavePath = (index != -1 ? spath.substring(0, index) : spath)
					+ "/" + dirName + "/";
			fileSavePath = fileSavePath.replaceAll("\\\\", "/");
			fileSavePath = fileSavePath.replaceAll("///", "/");
			fileSavePath = fileSavePath.replaceAll("//", "/");
			FileUtils.createDir(fileSavePath);
		}
	}

	/**
	 * 获取文件保存路径
	 * 
	 * @param request
	 */
	public String getFileSavePath() {
		return fileSavePath;
	}

	public void upload() {
		if (StringUtils.isNullOrEmpty(key)) {
			out("login timeout");
			return;
		}
		float fileSize = StringUtil.stringToFloat(
				FileUtils.siSheWuRu((uploadFile.length() / (float) 1024)), 0f);
		System.out.println(key + " upload file[" + fileName + "]...."
				+ fileSize + "KB");
		if (fileSize > fileMaxSize) {
			out("Exceeds the limit.");
			return;
		}
		if (key.equals("app_update")) {
			dirName = request.getSession().getServletContext().getContextPath()
					+ "/" + dirName + fileName + "/" + version;
			setFileSavePath2(request);
			fileName = fileName + ".zip";
		} else {
			dirName = request.getSession().getServletContext().getContextPath()
					+ "/" + dirName + key;
			setFileSavePath(request);
		}
		System.out.println("fileSavePath=" + fileSavePath);
		try {
			// 以服务器的文件保存地址和原文件名建立上传文件输出流
			FileOutputStream fos = new FileOutputStream(getFileSavePath()
					+ fileName);
			// 以上传文件建立一个文件上传流
			FileInputStream fis = new FileInputStream(getUploadFile());
			// 将上传文件的内容写入服务器
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}
			fis.close();
			fos.flush();
			fos.close();
			out("1");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void download() {
		String id = request.getParameter("id");
		dirName = dirName + id;
		setFileSavePath(request);
		File files = new File(getFileSavePath());
		if (files.exists()) {
			File[] fileArr = files.listFiles();
			Map<String, String> fb = null;
			File file = null;
			List<Map<String, String>> list = new ArrayList<Map<String, String>>();
			for (int i = 0, k = fileArr.length; i < k; i++) {
				file = fileArr[i];
				fb = new HashMap<String, String>();
				fb.put("fileName", file.getName());
				fb.put("filePath", file.getAbsolutePath());
				fb.put("fileUrl", "d=" + id + "&n=" + file.getName());
				list.add(fb);
			}
			JSONArray json = JSONArray.fromObject(list);
			out(json.toString());
		}
	}

	public void out(String msg) {
		try {
			PrintWriter pw = response.getWriter();
			pw.write(msg);
			pw.flush();
			pw.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	public void setFileMaxSize(float fileMaxSize) {
		this.fileMaxSize = fileMaxSize;
	}

	public float getFileMaxSize() {
		return fileMaxSize;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}
}
